/**
 * 各种模式下公用函数集合。<br>
 *
 * @namespace public
 * @author Don Li <kai.li@chivox.com>
 * @licence
 * Copyright (c) 2017 - 2020 ChiVox Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import Utils from '../utils';

/**
 * 公用的TTS(Text To Speech)转换函数，以HTTP FORM的方式提交TTS参数，并下载转换后的音频。
 *
 * @param {Object} options - TTS转换所需的参数，详细如下：
 * @param {string} options.uid - TTS转换所需的uid
 * @param {string} options.appkey - TTS转换所需的appKey
 * @param {string} options.sig - TTS转换所需的sig
 * @param {string} options.timestamp - TTS转换所需的timestamp
 * @param {string} options.text - 要转换的文本
 * @param {string} options.coreType - 要使用的TTS内核
 * @param {string} options.resource - 要使用的TTS资源
 * @return {int} - 会直接下载转换后的音频，如有其它需求，可以参考这个函数实现，用http post的方式来模拟。
 */
export function tts(options) {
    var x = this;
    if (x.__synthStarted
            || typeof options == "undefined"
            || typeof options.uid == "undefined"
            || typeof options.appkey == "undefined"
            || typeof options.timestamp == "undefined"
            || typeof options.sig == "undefined"
            || typeof options.text == "undefined"
            || typeof options.coreType == "undefined"
            || typeof options.resource == "undefined") {

        x.options.onError("tts failed, check param options plz", options, x.__synthStarted);
        return false;
    }

    var url = cfg.tts_url + "/" + options.coreType + "/" + options.resource;

    options.ip = "1.1.1.1";
    options.audio_type = "mp3";
    options.channel = 1;
    options.sample_rate = 16000;
    options.sample_bytes = 2;
    options.request = '{"refText": "'+ options.text + '"}';

    delete options.coreType;
    delete options.resource;
    delete options.text;

    x.__synthStarted = true;

    var tmp_form = document.getElementById('frmTTS');

    if (tmp_form) {
        tmp_form.parentNode.removeChild(tmp_form);
    }

    tmp_form = document.createElement("form");
    tmp_form.id = 'frmTTS';

    tmp_form.style.display = 'none';

    tmp_form.setAttribute('action', url);
    tmp_form.setAttribute('enctype', 'multipart/form-data');
    tmp_form.setAttribute('method', 'POST');
    tmp_form.setAttribute('target', '_SELF');

    for (var param in options) {
        var tmp_input = document.createElement('input');
        tmp_input.setAttribute('name', param);
        tmp_input.setAttribute('value', options[param]);

        tmp_form.appendChild(tmp_input);
    }

    document.body.appendChild(tmp_form);
    tmp_form.submit();

    x.__synthStarted = false;

    return false;
};

/**
 * 废弃函数。JS版的sig和timestamp生成算法。
 */
export function get_sig(params) {
    if (!this.options.sigurl || this.options.sigurl == '') {
        this.options.onError('sigurl not set!');
    } else {
        Utils.ajax({
            url: this.options.sigurl,
            querystring: this.options.alg,
            type: 'POST',
            dataType: 'json'
        }).then(
            (json) => {
                this.options.timestamp = json.timestamp;
                this.options.sig = json.sig;
                this.record(params);
            }).catch(
                (err) => { this.options.onError(`get sig failed, caused by: ${err}`); }
                );
    }
};
